var uuid = require("uuid");
var MongoClient = require("../../../command/MongoClient");
var dispatcher = require('../../../util/dispatcher');

module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next stemp callback
 *
 */
handler.queryEntry = function(msg, session, next) {
	var uid = msg.uid;
	// get all connectors
	var connectors = this.app.getServersByType('connector');
	if(!connectors || connectors.length === 0) {
		next(null, {
			code: 500
		});
		return;
	}

	MongoClient.init();

	// select connector
	
	if(!uid){
		uid = uuid.v4();
		MongoClient.insert({uid: uid, level: 1, score: 0, lastPlayTime: Date.now()}, function(data){
			MongoClient.close();
			var res = dispatcher.dispatch(uid, connectors);
			next(null, {
				code: 200,
				host: res.host,
				port: res.clientPort,
				uid: uid
			});
		});
	}else{
		MongoClient.find({uid: uid}, function(data){
			if(data.length > 0){
				var res = dispatcher.dispatch(uid, connectors);
				next(null, {
					code: 200,
					host: res.host,
					port: res.clientPort,
					uid: uid
				});
			}else{
				MongoClient.insert({uid: uid, level: 1, score: 0, lastPlayTime: Date.now()}, function(data){
					MongoClient.close();
					var res = dispatcher.dispatch(uid, connectors);
					next(null, {
						code: 200,
						host: res.host,
						port: res.clientPort,
						uid: uid
					});
				});
			}
		});
		
	}
	
	
};
